package main

import (
	"github.com/cihub/seelog"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
	"wallet/controllers"
	"wallet/helpers"
	"wallet/models"
)

func main() {
	r := gin.Default()

	store := sessions.NewCookieStore([]byte("secret123"))
	store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"}) //Also set Secure: true if using SSL, you should though
	r.Use(sessions.Sessions("wallet-session", store))

	r.Static("/static", "./static")
	funcMaps := template.FuncMap{
		"dateFormat": helpers.DateFormat,
		"add":        helpers.Add,
	}
	r.SetFuncMap(funcMaps)
	r.LoadHTMLGlob("templates/*")

	r.GET("/", controllers.IndexGet)
	r.GET("/index", controllers.IndexGet)

	// auth
	r.POST("/login", controllers.LoginPost)
	r.POST("/user", controllers.SignupPost)
	r.GET("/logout", controllers.Logout)

	authorized := r.Group("/admin")
	authorized.Use(AuthRequired())
	{
		authorized.GET("/index", controllers.HomeGet)

		// book
		authorized.POST("/new_book", controllers.BookCreate)
		authorized.GET("/books", controllers.BookIndex)

		// userbook
		authorized.POST("/userbook/add", controllers.UserBookCreate)

		// bills
		authorized.POST("/new_bill", controllers.BillCreate)
		authorized.GET("/bills/:bookid", controllers.BillIndex)
		authorized.GET("/bill/:id/delete", controllers.BillDelete)
	}

	r.Run(":8090") // listen and serve on 0.0.0.0:8080
}

func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		if user := session.Get(controllers.SESSION_USER); user != nil {
			if _, ok := user.(*models.User); ok {
				c.Next()
				return
			}
		}
		seelog.Warnf("User not authorized to visit %s", c.Request.RequestURI)
		c.AbortWithStatus(http.StatusUnauthorized)
	}
}
